import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Plus,
  Upload,
  Trash2,
  MapPin,
  Loader2,
  Edit,
  Eye,
  ChevronLeft,
  ChevronRight,
  MoreHorizontal,
  Search,
} from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import CrossingPointImportModal from "@/components/crossingpoints/CrossingPointImportModal";
import CrossingPointForm from "../crossingpoints/CrossingPointForm";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { DictDataAPI, DictTypeAPI } from "@/api/dictionary";

// 常量定义
const CONSTANTS = {
  difficultyTexts: {
    low: "低",
    medium: "中等",
    high: "高",
    critical: "极高",
  },
  priorityTexts: {
    low: "低",
    medium: "中等",
    high: "高",
    urgent: "紧急",
  },
  statusTexts: {
    planning: "规划中",
    designed: "已设计",
    approved: "已批准",
    construction: "施工中",
    completed: "已完成",
  },
};

// 颜色工具函数
const getDifficultyColor = (level) => {
  const colors = {
    low: "bg-green-100 text-green-800 border-green-200",
    medium: "bg-yellow-100 text-yellow-800 border-yellow-200",
    high: "bg-orange-100 text-orange-800 border-orange-200",
    critical: "bg-red-100 text-red-800 border-red-200",
  };
  return colors[level] || colors.medium;
};

const getPriorityColor = (priority) => {
  const colors = {
    low: "bg-gray-100 text-gray-800 border-gray-200",
    medium: "bg-blue-100 text-blue-800 border-blue-200",
    high: "bg-orange-100 text-orange-800 border-orange-200",
    urgent: "bg-red-100 text-red-800 border-red-200",
  };
  return colors[priority] || colors.medium;
};

const getStatusColor = (status) => {
  const colors = {
    planning: "bg-gray-100 text-gray-800 border-gray-200",
    designed: "bg-blue-100 text-blue-800 border-blue-200",
    approved: "bg-green-100 text-green-800 border-green-200",
    construction: "bg-yellow-100 text-yellow-800 border-yellow-200",
    completed: "bg-emerald-100 text-emerald-800 border-emerald-200",
  };
  return colors[status] || colors.planning;
};

// 数值格式化函数
const formatNumber = (value) => {
  if (value === null || value === undefined || value === "") return "-";
  
  const num = parseFloat(value);
  if (isNaN(num)) return value;
  
  if (Number.isInteger(num)) {
    return num.toString();
  }
  
  return parseFloat(num.toFixed(2)).toString();
};

export default function ProjectCrossingPointsList({
  project,
  crossingPoints = [],
  onRefreshCrossingPoints,
}) {
  const { toast } = useToast();

  // 分页和搜索状态
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [searchTerm, setSearchTerm] = useState("");

  // 模态框状态
  const [isImportModalOpen, setIsImportModalOpen] = useState(false);
  const [showEditForm, setShowEditForm] = useState(false);
  const [showViewModal, setShowViewModal] = useState(false);
  const [editingPoint, setEditingPoint] = useState(null);
  const [viewingPoint, setViewingPoint] = useState(null);

  // 批量操作状态
  const [selectedPoints, setSelectedPoints] = useState(new Set());
  const [isDeleting, setIsDeleting] = useState(false);

  // 字典数据
  const [crossingTypes, setCrossingTypes] = useState([]);

  // 过滤当前项目的跨越点
  const projectPoints = crossingPoints?.filter((p) => p.projectId === project?.id) || [];

  // 获取跨越类型标签的函数
  const getCrossingTypeLabel = useCallback((type) => {
    const matchedItem = crossingTypes.find((item) => item.value === type);
    return matchedItem ? matchedItem.label : type || "-";
  }, [crossingTypes]);

  // 搜索过滤
  const filteredPoints = useMemo(() => {
    if (!searchTerm) return projectPoints;
    
    const term = searchTerm.toLowerCase();
    return projectPoints.filter((point) => {
      const nameMatch = point.name && point.name.toLowerCase().includes(term);
      const objectMatch = point.crossingObject && point.crossingObject.toLowerCase().includes(term);
      const typeMatch = point.crossingType && getCrossingTypeLabel(point.crossingType).toLowerCase().includes(term);
      
      return nameMatch || objectMatch || typeMatch;
    });
  }, [projectPoints, searchTerm, getCrossingTypeLabel]);

  // 分页计算
  const totalItems = filteredPoints.length;
  const totalPages = Math.max(1, Math.ceil(totalItems / itemsPerPage));
  const startIndex = (currentPage - 1) * itemsPerPage;
  const paginatedPoints = filteredPoints.slice(startIndex, startIndex + itemsPerPage);

  // 确保当前页不超出范围
  useEffect(() => {
    if (currentPage > totalPages && totalPages > 0) {
      setCurrentPage(totalPages);
    }
  }, [currentPage, totalPages]);

  // 获取跨越类型字典数据
  const loadCrossingTypeOptions = useCallback(async () => {
    try {
      const typeResponse = await DictTypeAPI.getList();
      const crossingType = typeResponse.rows?.find((item) => item.dictName === "跨越类型");
      if (!crossingType) return;

      const dataResponse = await DictDataAPI.getList({ dictType: crossingType.dictType });
      const validTypes = (dataResponse.rows || [])
        .filter((item) => item.dictValue && item.dictLabel)
        .map((item) => ({
          value: item.dictValue,
          label: item.dictLabel,
        }));

      setCrossingTypes(validTypes);
    } catch (error) {
      console.error("加载跨越类型失败:", error);
    }
  }, []);

  useEffect(() => {
    loadCrossingTypeOptions();
  }, [loadCrossingTypeOptions]);

  // 分页处理
  const handlePageChange = (page) => {
    if (page < 1 || page > totalPages) return;
    setCurrentPage(page);
  };

  const handleItemsPerPageChange = (size) => {
    setItemsPerPage(size);
    setCurrentPage(1);
  };

  // 选择处理
  const handleSelectPoint = (pointId) => {
    setSelectedPoints(prev => {
      const newSet = new Set(prev);
      newSet.has(pointId) ? newSet.delete(pointId) : newSet.add(pointId);
      return newSet;
    });
  };

  const handleSelectAll = () => {
    setSelectedPoints(prev => 
      prev.size === filteredPoints.length && filteredPoints.length > 0
        ? new Set()
        : new Set(filteredPoints.map(p => p.id))
    );
  };

  // 跨越点操作
  const handleAddNew = () => {
    setEditingPoint({
      projectId: project.id,
      status: "planning",
      difficultyLevel: "medium",
      priority: "medium",
    });
    setShowEditForm(true);
  };

  const handleEdit = (point) => {
    setEditingPoint({ ...point });
    setShowEditForm(true);
  };

  // 名称点击处理函数
  const handleNameClick = (point, event) => {
    // 防止事件冒泡，避免触发行选择
    event.stopPropagation();
    handleEdit(point);
  };

  const handleView = (point) => {
    setViewingPoint({ ...point });
    setShowViewModal(true);
  };

  const handleEditSubmit = async (pointData) => {
    try {
      if (editingPoint?.id) {
        await CrossingPointAPI.update(editingPoint.id, pointData);
        toast({ title: "成功", description: "跨越点已更新" });
      } else {
        await CrossingPointAPI.create({ ...pointData, projectId: project.id });
        toast({ title: "成功", description: "跨越点已创建" });
      }
      setShowEditForm(false);
      setEditingPoint(null);
      onRefreshCrossingPoints?.();
    } catch (error) {
      toast({
        variant: "destructive",
        title: "错误",
        description: "保存失败: " + (error.message || "未知错误"),
      });
    }
  };

  const handleDelete = async (pointId) => {
    if (!window.confirm("确定要删除这个跨越点吗？此操作不可撤销。")) return;

    try {
      await CrossingPointAPI.delete(pointId);
      toast({ title: "成功", description: "跨越点已删除" });
      onRefreshCrossingPoints?.();
    } catch (error) {
      toast({
        variant: "destructive",
        title: "错误",
        description: "删除失败: " + (error.message || "未知错误"),
      });
    }
  };

  const handleBatchDelete = async () => {
    if (selectedPoints.size === 0) {
      toast({ title: "提示", description: "请先选择要删除的跨越点" });
      return;
    }

    if (!window.confirm(`确定要删除选中的 ${selectedPoints.size} 个跨越点吗？此操作不可撤销。`)) {
      return;
    }

    try {
      setIsDeleting(true);
      let successCount = 0;

      for (const pointId of selectedPoints) {
        try {
          await CrossingPointAPI.delete(pointId);
          successCount++;
        } catch (error) {
          console.error(`删除跨越点 ${pointId} 失败:`, error);
        }
      }

      toast({ title: "成功", description: `成功删除 ${successCount} 个跨越点` });
      setSelectedPoints(new Set());
      onRefreshCrossingPoints?.();
    } catch (error) {
      toast({
        variant: "destructive",
        title: "错误",
        description: "批量删除过程中发生错误",
      });
    } finally {
      setIsDeleting(false);
    }
  };

  const handleImportSuccess = () => {
    setIsImportModalOpen(false);
    onRefreshCrossingPoints?.();
    toast({ title: "成功", description: "跨越点导入成功" });
  };

  // 分页组件 - 与杆塔列表保持一致
  const renderPagination = () => {
    const getPageNumbers = () => {
      const pages = [];
      const maxVisiblePages = 5;

      if (totalPages <= maxVisiblePages) {
        for (let i = 1; i <= totalPages; i++) {
          pages.push(i);
        }
      } else {
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        if (startPage > 1) {
          pages.push(1);
          if (startPage > 2) {
            pages.push(null);
          }
        }

        for (let i = startPage; i <= endPage; i++) {
          pages.push(i);
        }

        if (endPage < totalPages) {
          if (endPage < totalPages - 1) {
            pages.push(null);
          }
          pages.push(totalPages);
        }
      }

      return pages;
    };

    const pageNumbers = getPageNumbers();

    return (
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
        <div className="text-sm text-gray-500">
          共 {totalItems} 条数据，显示
          {startIndex + 1} 到
          {Math.min(startIndex + itemsPerPage, totalItems)} 条
        </div>
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm" className="h-8">
                每页 {itemsPerPage} 条
                <MoreHorizontal className="ml-2 h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {[5, 10, 20, 50].map((count) => (
                <DropdownMenuItem
                  key={count}
                  onClick={() => handleItemsPerPageChange(count)}
                >
                  {count} 条/页
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
              aria-label="上一页"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>

            {pageNumbers.map((pageNum, index) => (
              pageNum === null ? (
                <span key={`ellipsis-${index}`} className="flex items-center justify-center h-8 w-8 text-gray-400">
                  ...
                </span>
              ) : (
                <Button
                  key={pageNum}
                  variant={currentPage === pageNum ? "default" : "outline"}
                  size="icon"
                  className="h-8 w-8"
                  onClick={() => handlePageChange(pageNum)}
                  aria-label={`第 ${pageNum} 页`}
                >
                  {pageNum}
                </Button>
              )
            ))}

            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
              aria-label="下一页"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>
    );
  };

  if (!project) {
    return (
      <Card className="mt-8 shadow-lg border-0">
        <CardContent className="py-12 text-center">
          <MapPin className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <p className="text-gray-500">未选择项目，请先选择项目</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card className="mt-8 shadow-lg border-0">
        <CardHeader className="bg-gradient-to-r from-indigo-50 to-blue-50 border-b">
          <div className="flex items-center justify-between">
            <CardTitle className="text-xl font-bold text-gray-800 flex items-center gap-2">
              <MapPin className="w-6 h-6 text-blue-600" />
              交叉跨越点清单
            </CardTitle>
            <div className="flex items-center gap-2">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                <Input
                  placeholder="搜索跨越点名称或对象..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-9 w-64"
                />
              </div>
              <Button onClick={handleAddNew} variant="outline">
                <Plus className="w-4 h-4 mr-2" />
                新增跨越点
              </Button>
              <Button onClick={() => setIsImportModalOpen(true)}>
                <Upload className="w-4 h-4 mr-2" />
                批量导入
              </Button>
            </div>
          </div>

          {/* 批量操作栏 */}
          {selectedPoints.size > 0 && (
            <div className="flex items-center justify-between pt-3 border-t mt-3">
              <div className="flex items-center gap-3">
                <Checkbox
                  checked={selectedPoints.size === filteredPoints.length && filteredPoints.length > 0}
                  onCheckedChange={handleSelectAll}
                />
                <span className="text-sm text-gray-600">
                  已选择 {selectedPoints.size} 个跨越点
                </span>
              </div>
              <Button
                onClick={handleBatchDelete}
                variant="destructive"
                size="sm"
                disabled={isDeleting}
              >
                {isDeleting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                    删除中...
                  </>
                ) : (
                  <>
                    <Trash2 className="w-4 h-4 mr-1" />
                    批量删除
                  </>
                )}
              </Button>
            </div>
          )}
        </CardHeader>

        <CardContent className="p-6 pt-0">
          {filteredPoints.length > 0 ? (
            <>
              <div className="overflow-x-auto pt-6">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-12">
                        <Checkbox
                          checked={selectedPoints.size === filteredPoints.length && filteredPoints.length > 0}
                          onCheckedChange={handleSelectAll}
                        />
                      </TableHead>
                      <TableHead>名称</TableHead>
                      <TableHead>跨越对象</TableHead>
                      <TableHead>跨越类型</TableHead>
                      <TableHead>宽度(m)</TableHead>
                      <TableHead>档距(m)</TableHead>
                      <TableHead>难度</TableHead>
                      <TableHead>优先级</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead className="text-right">操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {paginatedPoints.map((point) => (
                      <TableRow key={point.id} className="hover:bg-gray-50">
                        <TableCell>
                          <Checkbox
                            checked={selectedPoints.has(point.id)}
                            onCheckedChange={() => handleSelectPoint(point.id)}
                          />
                        </TableCell>
                        <TableCell 
                          className="font-medium hover:text-blue-600 hover:underline cursor-pointer transition-colors"
                          onClick={(e) => handleNameClick(point, e)}
                          title="点击编辑跨越点"
                        >
                          {point.name || "未命名跨越点"}
                        </TableCell>
                        <TableCell>{point.crossingObject || "-"}</TableCell>
                        <TableCell>{getCrossingTypeLabel(point.crossingType)}</TableCell>
                        <TableCell>
                          {point.crossedObjectWidth ? formatNumber(point.crossedObjectWidth) : "-"}
                        </TableCell>
                        <TableCell>
                          {point.spanLength ? formatNumber(point.spanLength) : "-"}
                        </TableCell>
                        <TableCell>
                          <Badge className={`${getDifficultyColor(point.difficultyLevel)} border`}>
                            {CONSTANTS.difficultyTexts[point.difficultyLevel] || "未知"}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge className={`${getPriorityColor(point.priority)} border`}>
                            {CONSTANTS.priorityTexts[point.priority] || "未知"}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge className={`${getStatusColor(point.status)} border`}>
                            {CONSTANTS.statusTexts[point.status] || "未知"}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            {/* <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleView(point)}
                              title="查看"
                            >
                              <Eye className="w-4 h-4" />
                            </Button> */}
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEdit(point)}
                              title="编辑"
                            >
                              <Edit className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDelete(point.id)}
                              className="text-red-600 hover:text-red-700"
                              title="删除"
                            >
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              {renderPagination()}
            </>
          ) : (
            <div className="text-center py-12 border-2 border-dashed border-gray-200 rounded-lg">
              <MapPin className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <p className="text-gray-500 mb-2">
                {searchTerm ? "未找到匹配的跨越点" : "该项目下暂无交叉跨越点"}
              </p>
              <p className="text-sm text-gray-400 mb-4">请添加跨越点以继续</p>
              <div className="flex justify-center gap-3">
                <Button onClick={handleAddNew}>
                  <Plus className="w-4 h-4 mr-2" />
                  新增第一个跨越点
                </Button>
                {searchTerm && (
                  <Button variant="outline" onClick={() => setSearchTerm("")}>
                    清除搜索
                  </Button>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 导入模态框 */}
      <CrossingPointImportModal
        isOpen={isImportModalOpen}
        onClose={() => setIsImportModalOpen(false)}
        projectId={project.id}
        onImportSuccess={handleImportSuccess}
      />

      {/* 编辑表单 */}
      {showEditForm && (
        <CrossingPointForm
          point={editingPoint}
          projects={[project]}
          onSubmit={handleEditSubmit}
          onCancel={() => {
            setShowEditForm(false);
            setEditingPoint(null);
          }}
          isStandalone={false}
          isReadOnly={false}
        />
      )}

      {/* 查看表单 */}
      {showViewModal && viewingPoint && (
        <CrossingPointForm
          point={viewingPoint}
          projects={[project]}
          onSubmit={() => setShowViewModal(false)}
          onCancel={() => setShowViewModal(false)}
          isStandalone={false}
          isReadOnly={true}
        />
      )}
    </>
  );
}